package com.mwx.baselib.base;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;


/**
 * Fragment父类
 */
public abstract class BaseFragmentLazy extends Fragment {

    private String TAG ;
    protected View mRootView;
    protected Context mContext;
    /** Fragment当前状态是否可见 */
    protected boolean isVisible;
    /** 标志位，标志已经初始化完成 */
    protected boolean isPrepared;
    /** 是否已被加载过一次，第二次就不再去请求数据了 */
    protected boolean mHasLoadedOnce;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mContext = getActivity();
        if (null == mRootView) {
            mRootView = inflater.inflate(getContentLayout(), container, false);
            TAG=this.getClass().getSimpleName();
//            mToolbar = (Toolbar) mRootView.findViewById(R.id.toolbar);

            initView();
        } else {
            ViewGroup parent = (ViewGroup) mRootView.getParent();
            if (null != parent) {
                parent.removeView(mRootView);
            }
        }
        return mRootView;
    }


    protected abstract int getContentLayout();
    protected abstract void initData();

    public void initView(){
        isPrepared=true;
        lazyLoad();
    }


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);

        if(getUserVisibleHint()) {
            isVisible = true;
            onVisible();
        } else {
            isVisible = false;
            onInvisible();
        }
    }


    /**
     * 可见
     */
    protected void onVisible() {
        lazyLoad();
    }


    /**
     * 不可见
     */
    protected void onInvisible() {


    }


    /**
     * 延迟加载
     * 子类必须重写此方法
     */
//    protected abstract void lazyLoad();

    /**
     * 延迟加载
     * 子类必须重写此方法
     */
    protected void lazyLoad() {
        if(!isPrepared||!isVisible||mHasLoadedOnce){
            return;
        }
        initData();
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    /**
     * 具体在哪个部位显示加载中，加载失败，网络异常等
     * */
    protected View getLoadingTargetView() {
        return null;
    }

    public void onReload() {

    }
    /**
     * intent跳转
     * @param clazz
     */
    protected void openActivity( Class<? extends BaseActivity> clazz){
        Intent intent = new Intent(mContext,clazz);
        mContext.startActivity(intent);
    }    /**
     * intent带值跳转
     * @param clazz
     * @param bundle
     */
    protected void openActivity(Class<? extends BaseActivity> clazz, Bundle bundle){
        Intent intent = new Intent(mContext,clazz);
        intent.putExtras(bundle);
        mContext.startActivity(intent);
    }

}
